const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

// 评论模型定义 - 直接映射数据库表结构
const Comment = sequelize.define('Comment', {
  // 主键ID
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false
  },
  
  // 视频ID
  video_id: {
    type: DataTypes.BIGINT,
    allowNull: false,
    references: {
      model: 'videos',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  
  // 用户ID
  user_id: {
    type: DataTypes.BIGINT,
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  
  // 父评论ID
  parent_id: {
    type: DataTypes.BIGINT,
    allowNull: true,
    defaultValue: null,
    references: {
      model: 'comments',
      key: 'id'
    },
    onDelete: 'CASCADE'
  },
  
  // 评论内容
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
    validate: {
      notEmpty: {
        msg: '评论内容不能为空'
      },
      len: {
        args: [1, 1000],
        msg: '评论内容长度必须在1-1000个字符之间'
      }
    }
  },
  
  // 点赞数
  like_count: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    validate: {
      min: 0
    }
  },
  
  // 状态
  status: {
    type: DataTypes.TINYINT,
    allowNull: false,
    defaultValue: 1,
    validate: {
      isIn: {
        args: [[0, 1, 2]],
        msg: '状态值无效'
      }
    }
  },
  
  // 时间戳字段 - 直接使用数据库中的字段名
  created_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  
  updated_at: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW
  },
  
  deleted_at: {
    type: DataTypes.DATE,
    allowNull: true
  }
}, {
  // 表配置 - 简化配置，确保与数据库表名匹配
  tableName: 'comments',
  timestamps: false, // 禁用自动时间戳，使用手动定义的字段
  paranoid: false, // 禁用自动软删除，手动处理
  charset: 'utf8mb4',
  collate: 'utf8mb4_unicode_ci'
});

// 关联关系 - 使用标准方式定义
const User = require('./User');
const Video = require('./Video');

Comment.belongsTo(User, { 
  foreignKey: 'user_id', 
  as: 'user' 
});

Comment.belongsTo(Video, { 
  foreignKey: 'video_id', 
  as: 'video' 
});

Comment.belongsTo(Comment, { 
  foreignKey: 'parent_id', 
  as: 'parent' 
});

Comment.hasMany(Comment, { 
  foreignKey: 'parent_id', 
  as: 'replies' 
});

// 创建评论前的钩子
Comment.beforeCreate(async (comment) => {
  try {
    const Video = require('./Video');
    const video = await Video.findByPk(comment.video_id);
    if (video && typeof video.incrementCommentCount === 'function') {
      await video.incrementCommentCount();
    }
  } catch (error) {
    console.error('更新视频评论数失败:', error);
  }
});

// 删除评论前的钩子
Comment.beforeDestroy(async (comment) => {
  try {
    const Video = require('./Video');
    const video = await Video.findByPk(comment.video_id);
    if (video && typeof video.decrementCommentCount === 'function') {
      await video.decrementCommentCount();
    }
  } catch (error) {
    console.error('更新视频评论数失败:', error);
  }
});

// 实例方法：增加点赞数
Comment.prototype.incrementLikeCount = async function() {
  this.like_count += 1;
  await this.save();
  return this.like_count;
};

// 实例方法：减少点赞数
Comment.prototype.decrementLikeCount = async function() {
  this.like_count = Math.max(0, this.like_count - 1);
  await this.save();
  return this.like_count;
};

// 实例方法：切换点赞状态
Comment.prototype.toggleLike = async function() {
  if (typeof this.liked === 'undefined') {
    this.liked = false;
  }
  this.liked = !this.liked;
  
  if (this.liked) {
    this.like_count++;
  } else {
    this.like_count = Math.max(0, this.like_count - 1);
  }
  
  await this.save();
  
  return {
    liked: this.liked,
    likeCount: this.like_count
  };
};

// 类方法：根据视频ID获取评论列表
Comment.getCommentsByVideoId = async function(videoId, limit = 20, offset = 0, includeReplies = false) {
  const query = {
    where: {
      video_id: videoId,
      parent_id: null,
      status: 1
    },
    include: [
      {
        model: User,
        as: 'user',
        attributes: ['id', 'username', 'avatar']
      }
    ],
    order: [['created_at', 'DESC']],
    limit,
    offset
  };
  
  if (includeReplies) {
    query.include.push({
      model: Comment,
      as: 'replies',
      where: { status: 1 },
      required: false,
      order: [['created_at', 'ASC']],
      include: [
        {
          model: User,
          as: 'user',
          attributes: ['id', 'username', 'avatar']
        }
      ]
    });
  }
  
  return await this.findAll(query);
};

module.exports = Comment;

// 导出到全局
global.Comment = Comment;